package com.boss.thirteen.service.impl;

import com.boss.common.entity.PageDTO;
import com.boss.common.entity.WfActionDTO;
import com.boss.common.enums.StatusCodeEnum;
import com.boss.common.service.ICommonService;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.dao.IPersonTypeSalaryDao;
import com.boss.salary.entity.AgencyVerify;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import com.boss.thirteen.dao.ISalaryThirteenMonthDao;
import com.boss.thirteen.dao.ISalaryThirteenMouldDao;
import com.boss.thirteen.dao.IThirteenAgencyVerifyDao;
import com.boss.thirteen.entity.SalaryThirteenMonth;
import com.boss.thirteen.entity.ThirteenAgencyVerify;
import com.boss.thirteen.service.ISalaryThirteenMonthEndService;
import com.boss.thirteen.service.ISalaryThirteenWorkFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SalaryThirteenMonthEndServiceImpl implements ISalaryThirteenMonthEndService {
    @Autowired
    private ISalaryThirteenMonthDao salaryThirteenMonthDao;
    @Autowired
    private ISalaryThirteenWorkFlowService salaryThirteenWorkFlowService;
    @Autowired
    private IThirteenAgencyVerifyDao thirteenAgencyVerifyDao;
    @Autowired
    private IPersonTypeSalaryDao iPersonTypeSalaryDao;
    @Autowired
    private ISalaryThirteenMouldDao salaryThirteenMouldDao;
    @Autowired
    private ICommonService commonService;
    @Override
    public PageDTO<SalaryThirteenMonth> getUnitSalaryReportPage(PaginationDTO paginationDTO, String agencyId, String flag, Map<String, Object> condition, UserDTO userDTO, String menuid) throws AppRuntimeException {
//        查询当前月份，送审状态及工资变动状态
        PageDTO<SalaryThirteenMonth> pageDTO = new PageDTO<>();
        Map<String,Object> stateMap = thirteenAgencyVerifyDao.selectStateByAgencyId(agencyId,"biz_key");
        if(CollectionUtils.isEmpty(stateMap)){
            return pageDTO;
        }

//        判断当前处于哪一个tab页 0 未审核 1 已审核 -1 被退回 all 全部
        if(!"all".equals(flag)){
            //判断是否含有已办
            WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(menuid);
            List<String> statusList = new ArrayList<>();
            if("0".equals(flag)){
                statusList.add(StatusCodeEnum.TODO.getCode());//判断待办流程
            }
            if ("1".equals(flag)) {
                statusList.add(StatusCodeEnum.FINISHED.getCode());//判断已审核流程
            }
            if ("-1".equals(flag)) {
                statusList.add(StatusCodeEnum.BESENDBACK.getCode());//判断被退回流程
            }
            if ("0".equals(flag)) {
                statusList.add(StatusCodeEnum.RECALL.getCode());//判断已撤销流程
            }
            List<String> bizkeyList = new ArrayList<>();
            bizkeyList.add(stateMap.get("biz_key").toString());
            List<Map> maps = salaryThirteenWorkFlowService.queryWorkflowInfoStatus(userDTO, wfActionDTO, statusList, bizkeyList);
            for (Map map : maps) {
                if (StringUtils.isEmpty(map.get("status"))) {
                    return pageDTO;
                }
            }
        }

        List<SalaryThirteenMonth> result= salaryThirteenMonthDao.querySalaryThirteenMonthPage(paginationDTO, agencyId,  condition);
        List<String> childId=result.stream().map(SalaryThirteenMonth::getChildId).filter(id->null!=id).collect(Collectors.toList());
        if(!SysUtils.isNullOrEmpty(childId)){
            List<SalaryThirteenMonth> children=salaryThirteenMonthDao.selecctSalaryThirteenBeginById(childId);
            for(SalaryThirteenMonth stm:result){
                for(SalaryThirteenMonth cstm:children){
                    if(cstm.getId().equals(stm.getChildId())){
                        stm.setChildren(Collections.singletonList(cstm));
                        continue;
                    }
                }
            }
        }
        int total=salaryThirteenMonthDao.querySalaryThirteenMonthCount( agencyId,  condition);
        pageDTO.setRows(result);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    public PageDTO<Map<String,Object>> getVerifySalaryData(PaginationDTO paginationDTO, String agencyId, String flag, UserDTO userDTO, String menuId,Map<String,Object> otherParams) throws AppRuntimeException {
//        查询当前月份，送审状态及工资变动状态
        PageDTO<Map<String,Object>> pageDTO = new PageDTO<>();
        List<String> childrenId = commonService.getAgencyChildrenId(userDTO, agencyId);
        String bizKeys = "";
        WfActionDTO wfActionDTO = new WfActionDTO();
        // 菜单id
        wfActionDTO.setMenuguid(menuId);
        wfActionDTO.setBizKeyName("biz_key");
        wfActionDTO.setYear(userDTO.getYear()+"");
        wfActionDTO.setProvince(userDTO.getProvince());
        // 未确定
        if(!"all".equals(flag)) {
            if("0".equals(flag)){
                wfActionDTO.setStatus(StatusCodeEnum.TODO.getCode());//判断待办流程
            }
            if ("1".equals(flag)) {
                wfActionDTO.setStatus(StatusCodeEnum.FINISHED.getCode());//判断已审核流程
            }
            if ("-1".equals(flag)) {
                wfActionDTO.setStatus(StatusCodeEnum.BESENDBACK.getCode());//判断被退回流程
            }
            if ("-11".equals(flag)) {
                wfActionDTO.setStatus(StatusCodeEnum.TODO_BESENDBACK.getCode());//判断待办+被退回流程
            }
            bizKeys = commonService.getWorkflowWheresql(wfActionDTO, "av","salary_thirteen_verify");
        }
        List<Map<String,Object>> result= salaryThirteenMonthDao.selectVerifySalaryData(paginationDTO, bizKeys,childrenId,otherParams);
        int total=salaryThirteenMonthDao.selectVerifySalaryDataTotal( bizKeys,childrenId,otherParams);
        pageDTO.setRows(result);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    public PageDTO<ThirteenAgencyVerify> queryAgencySubmitStatus(PaginationDTO paginationDTO, String flag, UserDTO userDTO, String menuId) throws AppRuntimeException {
//        查询当前月份，送审状态及工资变动状态
        PageDTO<ThirteenAgencyVerify> pageDTO = new PageDTO<>();
        List<String> childrenId = commonService.getAgencyChildrenId(userDTO,"0");
        String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        Map<String,Object> params=new HashMap<>();
        params.put("mof_div_code",userDTO.getProvince());
        params.put("year",year);
        params.put("isSalarySubmit",flag);
        List<ThirteenAgencyVerify> tvs=thirteenAgencyVerifyDao.queryThirteenAgencyVerify(paginationDTO,params,childrenId);
        int total=thirteenAgencyVerifyDao.queryThirteenAgencyCount(params,childrenId);
        pageDTO.setRows(tvs);
        pageDTO.setTotal(total);
        return pageDTO;
    }
    @Override
    public List<String> getColumnName(String agencyId,Map<String,Object> condition,UserDTO userDTO,boolean flag) {
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        List<String> personTypes=new ArrayList<>();
        Object salaryType = condition.get("salaryType");
        if (!StringUtils.isEmpty(salaryType)) {
            personTypes.add(salaryType.toString());
        }else {
            personTypes = iPersonTypeSalaryDao.getAllPersonTypeByAgencyId(agencyId);
        }
        //获取人员类型查询工资项
        List<String> columnNameList=salaryThirteenMouldDao.queryMouldSalaryCodes(personTypes,userDTO.getProvince(),year);
        List<String> request=new ArrayList<>();
        for(String salaryCode:columnNameList){
            request.addAll(Arrays.asList(salaryCode.split(",")));
        }
        request=request.stream().distinct().collect(Collectors.toList());
        if(flag) {
            request.remove("s1");
            request.add("s1_compute");
        }
        return request;
    }

    public List<SalaryThirteenMonth> selectSalaryThirteenPersonFromHistory(String agencyId,String province){
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        return salaryThirteenMonthDao.selectSalaryThirteenPersonFromHistory(agencyId,year,province);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSalaryThirteenMonth(List<SalaryThirteenMonth> stms) throws Exception{
        salaryThirteenMonthDao.batchInsertSalaryThirteenMonth(stms);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateSalaryThirteenMonth(List<SalaryThirteenMonth> list) throws Exception {
        salaryThirteenMonthDao.batchUpdateSalaryThirteenMonth(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteThirteenMonth(List<String> ids) {
        salaryThirteenMonthDao.deleteSalaryThirteenMonth(ids);
    }

    @Override
    public Map<String, Object> queryThirteenCount(String agencyId) {
        Integer addCount=salaryThirteenMonthDao.queryAgencyAddCount(agencyId);
        Integer delCount=salaryThirteenMonthDao.queryAgencyDelCount(agencyId);
        Map<String, Object> beginMap=salaryThirteenMonthDao.queryAgencyBeginTotal(agencyId);
        Map<String, Object> map=salaryThirteenMonthDao.queryAgencyTotal(agencyId);
        map.putAll(beginMap);
        map.put("addCount",addCount);
        map.put("delCount",delCount);

        return map;
    }

    @Override
    public List<Map<String, Object>> queryThirteenChangePersonInfo(String agencyId) {
        List<Map<String, Object>> addList=salaryThirteenMonthDao.queryAgencyAddPersonInfo(agencyId);
        List<Map<String, Object>> delList=salaryThirteenMonthDao.queryAgencyDelPersonInfo(agencyId);
        List<Map<String, Object>> list=new ArrayList<>();
        list.addAll(addList);
        list.addAll(delList);
        return list;
    }
}
